package com.yuyu.qingmangmall.cart.interceptor;

import com.yuyu.common.constant.AuthServerConstant;
import com.yuyu.common.constant.CartConstant;
import com.yuyu.common.vo.SocialMemberVo;
import com.yuyu.qingmangmall.cart.to.UserInfoTo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 再执行方法前，判断用户的登陆状态。并封装传递给controller目标请求
 * ThreadLocal
 * 为ThreadLocal中存入数据，当前线程的其他类都可以调用存入的数据
 */
@Component
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    /**
     * 目标方法执行前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        HttpSession session = request.getSession();
        SocialMemberVo member = (SocialMemberVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        UserInfoTo userInfoTo = new UserInfoTo();
        if (member!=null){
            // 登陆状态
            userInfoTo.setUserId(member.getId());
        }
        // 创建临时用户  user-key


//        Cookie userKey = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, string);
//        response.addCookie(userKey);

        Cookie[] cookies = request.getCookies();
        if (cookies!=null && cookies.length>0){
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(CartConstant.TEMP_USER_COOKIE_NAME)){
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setTempUser(true);
                    break;
                }
            }
        }
        if (userInfoTo.getUserKey()==null){
            String string = UUID.randomUUID().toString();
            userInfoTo.setUserKey(string);
        }
//        userInfoTo.setUserKey(CartConstant.TEMP_USER_COOKIE_NAME);

        threadLocal.set(userInfoTo);
        return true;
    }

    /**
     * 业务执行之后，分配临时用户，让浏览器保存
     * 如果没有临时用户一定保存一个临时用户
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        if (!userInfoTo.getTempUser()){
            // 持续的延长临时用户的过期时间
            Cookie userKey = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            userKey.setDomain("qingmangmall.com");
            userKey.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(userKey);
        }
    }
}
